package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.alibaba.fastjson.JSON;
import com.iwhalecloud.citybrain.flow.platform.manager.application.event.EventResponse;
import com.iwhalecloud.citybrain.flow.platform.manager.application.event.NodeEventExecuter;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.MultiExecutionStartedProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.ParseRenderedVariable;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ConstanceVariable;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.EventCallException;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.eventconfig.DeployedEventConfigDomain;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.TaskVariableSetRequestVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowEventConfigRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.TaskVariableRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.Future;

/**
 * @author: liyang
 * @date: 2022/01/08 18:22
 */
@Slf4j
@Service
public class MultiExecutionStartedEventCallProcessor implements MultiExecutionStartedProcessor {

    @Autowired
    private NodeEventExecuter nodeEventExecuter;

    @Autowired
    private FlowEventConfigRepository flowEventConfigRepository;

    @Autowired
    private TaskVariableRepository taskVariableRepository;

    @Override
    public void process(ExecutionEntity execution) throws Exception {
        String activityId = execution.getActivityId();
        List<DeployedEventConfigDomain> eventConfigs = flowEventConfigRepository.getEventConfigList(
                String.valueOf(execution.getVariable(ConstanceVariable.DEPLOYMENT_ID)),activityId, FlowableEngineEventType.MULTI_INSTANCE_ACTIVITY_STARTED.name());
        if (CollectionUtils.isNotEmpty(eventConfigs)){
            for (DeployedEventConfigDomain eventConfig : eventConfigs) {
                String url = eventConfig.getCallbackContent();
                url = ParseRenderedVariable.parseRenderedVariable(url,execution);

                String requestBody = eventConfig.getRequestBody();
                if (StringUtils.isNotBlank(requestBody)){
                    requestBody = ParseRenderedVariable.parseRenderedVariable(requestBody,execution);
                }
                EventResponse eventResponse = null;
                if (Objects.equals("sync",eventConfig.getCallMethod())){
                    try {
                        eventResponse = nodeEventExecuter.syncCall(url,requestBody);
                        log.info("eventResponse:"+ JSON.toJSONString(eventResponse));
                    } catch (EventCallException eventCallException) {
                        log.error("execute multiTask started eventCall error", eventCallException);
                        throw eventCallException;
                    }
                }else{
                    try {
                        Future<EventResponse> asyncCall = nodeEventExecuter.asyncCall(url, requestBody);
                        try {
                            eventResponse = asyncCall.get();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        log.info("execute multiTask started eventCall success");
                    } catch (EventCallException eventCallException) {
                        log.error("execute multiTask started eventCall error", eventCallException);
                    }
                }
                if (StringUtils.isNotEmpty(eventConfig.getCallbackParam())){
                    if(eventResponse != null && eventResponse.isSuccess() && eventResponse.getDatas() != null){
                        Object responseData = eventResponse.getDatas();
                        TaskVariableSetRequestVo taskVariableSetRequestVo = new TaskVariableSetRequestVo();
                        taskVariableSetRequestVo.setKey(eventConfig.getCallbackParam());
                        taskVariableSetRequestVo.setValue(responseData);
                        taskVariableSetRequestVo.setProcessInstanceId(execution.getProcessInstanceId());
                        try {
                            taskVariableRepository.setTaskVariable(taskVariableSetRequestVo);
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("execute EventCall set param Error:",e);
                        }
                    }
                }
            }
        }
    }
}
